//
//  COMineMainController.swift
//  CocoProject
//
//  Created by Vill on 2023/11/7.
//

import UIKit

class COMineMainController: COBaseController {
    
    let minePicArr   = ["coco_mine_feedback","coco_mine_follow"]
    let mineTitleArr = ["Feedback","Follow"]
    
    var queryUserModel = COCurUserInfoModel()  // 个人资讯
    var followNum = 0                          // 关注数量
    
    // DispatchGroup-notify(不阻塞)
    let queueGroup = DispatchGroup()
    let queueQueue = DispatchQueue(label: "mine_queue", qos: DispatchQoS.default, attributes: DispatchQueue.Attributes.concurrent, autoreleaseFrequency: DispatchQueue.AutoreleaseFrequency.inherit, target: nil) // 创建并行队列
    
    lazy var baseTableView: UITableView = {
        let tableView = UITableView(frame: .zero, style: .plain)
        tableView.dataSource = self
        tableView.delegate = self
        tableView.backgroundColor = .clear
        tableView.tableFooterView = UIView()
        tableView.separatorStyle = .none
        tableView.showsVerticalScrollIndicator = false
        if #available(iOS 11.0, *) {
            if #available(iOS 13.0, *) {
                tableView.automaticallyAdjustsScrollIndicatorInsets = false
            }else{
                tableView.contentInsetAdjustmentBehavior = .never
            }
        }else {
            automaticallyAdjustsScrollViewInsets = false
        }
        return tableView
    }()
    
    lazy var setBtn: UIButton = {
        let set = UIButton(type: .custom)
        set.setImage(KImaged("coco_mine_setting"), for: .normal)
        set.addTarget(self, action: #selector(setAction), for: .touchUpInside)
        return set
    }()

    override func viewDidLoad() {
        super.viewDidLoad()
        view.addSubview(self.setBtn)
        self.setBtn.snp.makeConstraints { make in
            make.size.equalTo(PTW(44))
            make.left.equalToSuperview().offset(PTW(10))
            make.top.equalToSuperview().offset(KStatusAndNavBarHeight - PTW(44))
        }
        view.addSubview(self.baseTableView)
        self.baseTableView.snp.makeConstraints { make in
            make.left.right.bottom.equalToSuperview()
            make.top.equalToSuperview().offset(KStatusAndNavBarHeight)
        }
    }
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        kLiveCalling.keySaveToNSDefaults(with: false)
        self.baseTableView.reloadData()
        getMyData()
    }
    
    //MARK: ------------------- 获取个人信息 ------------------
    func getMyData(){
        queueGroup.enter()
        queueQueue.async { [weak self] in
            guard let `self` = self else { return }
            COHttpManager.request(target: COBaseApi.queryUser, modelType: COQueryUserModel.self) { code, object, success in
                self.queryUserModel = object?.user ?? COCurUserInfoModel()
                self.queueGroup.leave()
            } failureBlock: { code, msg in
                self.queueGroup.leave()
            }
        }
        queueGroup.enter()
        queueQueue.async { [weak self] in
            guard let `self` = self else { return }
            COHttpManager.request(target: COBaseApi.followCount, modelType: COFollowCountModel.self) { code, object, success in
                self.followNum = object?.count ?? 0
                self.queueGroup.leave()
            } failureBlock: { code, msg in
                self.queueGroup.leave()
            }
        }
        queueGroup.notify(queue: queueQueue) {
            DispatchQueue.main.safeAsync {
                self.setMyData()
            }
        }
    }
    
    func setMyData(){
        var model = COUserInfoManager.shared.curUser
        model?.userResponse = self.queryUserModel
        COUserInfoManager.shared.curUser = model
        COUserInfoManager.coSaveInfo()
        self.baseTableView.reloadData()
    }
    
    // 设置
    @objc func setAction(){
        self.navigationController?.pushViewController(COSetViewController(), animated: true)
    }
}

extension COMineMainController:UITableViewDelegate,UITableViewDataSource{
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return mineTitleArr.count+1
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        if indexPath.row == 0{
            let cell = COMineHeadTableCell().cellWithTableView(tableView)
            cell.selectionStyle = .none
            return cell
        }else{
            let cell = COMineListTableCell().cellWithTableView(tableView)
            cell.selectionStyle = .none
            cell.leftImg.image = KImaged(minePicArr[indexPath.row-1])
            cell.leftLbl.text = mineTitleArr[indexPath.row-1]
            if (indexPath.row == 1){
                cell.rightLbl.text = ""
            }else{
                cell.rightLbl.text = self.followNum > 0 ? "\(self.followNum)" : ""
            }
            return cell
        }
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        if indexPath.row == 0{
            return PTW(250)
        }else{
            return PTW(70)
        }
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        if (indexPath.row == 1){
            let feed = COFeedController()
            self.navigationController?.pushViewController(feed, animated: true)
        }else if (indexPath.row == 2){
            let follow = COFollowListController()
            self.navigationController?.pushViewController(follow, animated: true)
        }
    }
}
